/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapplication1;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 *
 * @author new
 */
public class QuotationHandler {

    public int changeQuote(String FileName) throws FileNotFoundException, IOException{
        String temp = "QuotationTemp";
        FileHandler fh = new FileHandler();
        BufferedReader br = fh.openReadFile(FileName);
        BufferedWriter bw = fh.openWriteFile(temp);
        String tempStr = br.readLine();
        while(tempStr != null){
            if(tempStr.contains("'") || tempStr.contains("\"")){
                tempStr = changeQuoteLine(tempStr);
            }
            bw.append(tempStr);
            bw.newLine();
            tempStr = br.readLine();
        }
        fh.closeReadFile(br);
        fh.closeWriteFile(bw);
        System.gc();
        fh.replaceFile(temp, FileName);
        return 0;
        
    }

    private String changeQuoteLine(String temp){
        String result = new String(temp);
        while(result.contains("\"")){
            int first = result.indexOf("\"");
            int second = result.indexOf("\"", first + 1);
            if(second == -1){
                System.out.println("Miss a \".");
                System.exit(0);
            }
            int length = second - first - 1;
            if(length == 0){
                System.out.println("\"\" quote nothing.");
                System.exit(0);
            }
            String tempStr = "";
            for(int i = 0; i < length; i++){
                int tempDec = (int) result.charAt(first + i + 1);
                if(tempDec < 16){
                    tempStr = tempStr + "0" + Integer.toHexString(tempDec);
                } else {
                    tempStr = tempStr + Integer.toHexString(tempDec);
                }
            }
            tempStr = tempStr + "H";
            result = result.substring(0, first) + tempStr + result.substring(second + 1);
        }
        while(result.contains("'")){
            int first = result.indexOf("'");
            int second = result.indexOf("'", first + 1);
            if(second == -1){
                System.out.println("Miss a '.");
                System.exit(0);
            }
            if(second - first == 1){
                System.out.println("'' quote nothing.");
                System.exit(0);
            }
            if(second - first != 2){
                System.out.println("'' cannot quote string.");
                System.exit(0);
            }
            result = result.substring(0, first) + (int) result.charAt(first + 1) + result.substring(second + 1);
        }

        return result;
    }
}
